﻿using System.Windows.Forms;
using WorkLogger.Client.DataAccess.Model;
using WorkLogger.Client.Forms;

namespace WorkLogger.Client.Services {
	public class LunchCheckService {
		private readonly IWorkDayManager workDayManager;
		private readonly ISystemClock systemClock;
		private readonly AppOptions appOptions;

		public LunchCheckService(IWorkDayManager workDayManager, ISystemClock systemClock, AppOptions appOptions) {
			this.workDayManager = workDayManager;
			this.systemClock = systemClock;
			this.appOptions = appOptions;
		}

		public void Check() {
			WorkDay workDay = workDayManager.GetCurrentWorkDay();

			if (workDay.LastWorkMoment == null)
				return;

			var lunchTime = new LunchTime {
			                              	StartLunch = workDay.LastWorkMoment.Value,
			                              	EndLunch = systemClock.Now,
			                              	WorkDay = workDay
			                              };

			var totalMinutesAbsent = (int)(lunchTime.GetDuration()).TotalMinutes;
			if (totalMinutesAbsent < appOptions.CoffeeBreak)
				return;

			using (var form = new AskAbsentForm()) {
				form.TopMost = true;
				form.AbsentDuration = lunchTime.GetDuration();

				if (form.ShowDialog() == DialogResult.OK) {
					workDay.LunchTimes.Add(lunchTime);
				}
				workDay.EndWork = systemClock.Now;
				workDay.LastWorkMoment = systemClock.Now;
				workDayManager.Update();
			}
		}
	}
}